package com.book.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.book.dao.UserDao;
import com.book.entity.vo.UserVo;
import com.book.exception.GlobalException;
import com.book.utils.JwtUtils;
import com.book.utils.PageUtils;
import com.book.utils.R;
import com.book.utils.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.book.entity.UserEntity;
import com.book.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author yang
 * @email yang@gmail.com
 * @date 2020-12-05 15:32:33
 */

@RestController
@RequestMapping("/book/user")
public class UserController {
    @Autowired
    private UserService userService;


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) throws JsonProcessingException {
        PageUtils page = userService.queryPage(params);

//        UserEntity userEntity = new UserEntity();
//        userEntity.setUsername("zhangsan");
//        ObjectMapper objectMapper = new ObjectMapper();
//        String s = objectMapper.writeValueAsString(userEntity);
//        redisTemplate.opsForValue().set("admin1206",s);
//        String admin1206 = (String) redisTemplate.opsForValue().get("admin1206");
//        UserEntity u2 = objectMapper.readValue(admin1206, UserEntity.class);
//        u2.setEmail("abc@qq.com");
//        System.out.println("redis~~~~~~~" + u2);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		UserEntity user = userService.getById(id);
        return R.ok().put("user", user);
    }



    @PostMapping("/token/login")
    public R login(@RequestBody UserVo userVo, HttpServletResponse response){
        String token = userService.login(userVo);
        Cookie cookie = new Cookie("JESSIONJWT",token);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 30);
        response.addCookie(cookie);
        return R.ok().put("token",token);
    }



    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody UserVo user){
		userService.saveUser(user);

        return R.ok();
    }

    @PostMapping("/get/sms/{photo}")
    public R sendSMS(@PathVariable("photo") String photo){
        String fourBitRandom = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",fourBitRandom);
        String Photo_ = "Photo_" + photo;
        boolean isSend =  userService.sendMsm(photo,param);
        if(isSend){
            redisTemplate.opsForValue().set(Photo_,fourBitRandom,5, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error("短信发送失败！！");

    }


    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		userService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @PostMapping("/verify/jwt/{token}")
    public R getUserInfoByToken(@PathVariable("token") String token){


        try {
            String username = JwtUtils.getUsernameByJwtToken(token);
            String id = JwtUtils.getIdByJwtToken(token);
            return R.ok().put("username",username).put("userId",id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(500,"token不合法或者已经过期！！");
        }

    }

    @PostMapping("/verify/jwt/cookie")
    public R getUserInfo(HttpServletRequest request){

        if(JwtUtils.checkToken(request)){
            String username = JwtUtils.getUsernameByJwtToken(request);
            String id = JwtUtils.getIdByJwtToken(request);
            return R.ok().put("username",username).put("userId",id);
        }else{
            throw new GlobalException(500,"token不合法或者已经过期！！");
        }



    }


}
